package data.databases;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.util.Log;

/** 
 * CONNECTION CLASS 
 * 
 */

public class MySQL {
	/* 
	 * Declarations 
	 */
	private final String BASE_URL = "http://145.81.4.161/EyePark/";
	
	private ArrayList<NameValuePair> params;
	private ArrayList<NameValuePair> headers;
	
	private int responseCode;
	private String message;
	
	private String response;
	 
	/* 
	 * Getters 
	 */
	public String getResponse() {
		return response;
	}
	
	public String getErrorMessage() {
		return message;
	}
	
	public int getResponseCode() {
		return responseCode;
	}	
	
	/*
	 * Setters
	 */
	public void AddParam(String name, String value) {
		params.add(new BasicNameValuePair(name, value));
	}
	
	public void AddHeaders(String name, String value) {
		headers.add(new BasicNameValuePair(name, value));
	}	
	
	/* 
	 * Constructors
	 */
	public MySQL() { 
		this.params = new ArrayList<NameValuePair>();
		this.headers = new ArrayList<NameValuePair>();
	}

	/*
	 * Functions
	 */
	public void Execute(RequestMethod method, String scriptname) throws Exception {
		switch(method) {
			case GET:
			{
				String combinedParams = "";
				if(!params.isEmpty()) {
					combinedParams += "?";
					for(NameValuePair pair : params) {
						String paramString = pair.getName() + "=" + URLEncoder.encode(pair.getValue(),"UTF-8");
						if(combinedParams.length() > 1) {
							combinedParams += "&" + paramString;
						}
						else {
							combinedParams += paramString;
						}
					}
				}
				String url = BASE_URL + scriptname + combinedParams;
				HttpGet request = new HttpGet(url);
				
				/* Add Headers */
				for(NameValuePair pair : headers) {
					request.addHeader(pair.getName(), pair.getValue());
				}
				
				executeRequest(request, url);
				break;
			}
			case POST:
			{
				String url = BASE_URL + scriptname;
				HttpPost request = new HttpPost(url);
				
				/* Add Headers */
				for (NameValuePair pair : headers) {
					request.addHeader(pair.getName(), pair.getValue());
				}
				
				if(!params.isEmpty()) {
					request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				}
				
				executeRequest(request, url);
				break;
			}
			case PUT:
			{
				break;
			}
			case DELETE:
			{
				break;
			}
		}
	}
	
	private void executeRequest(HttpUriRequest request, String url) {
		HttpClient client = new DefaultHttpClient();		
		HttpResponse httpResponse;
		
		try {
			httpResponse = client.execute(request);
			responseCode = httpResponse.getStatusLine().getStatusCode();
			message = httpResponse.getStatusLine().getReasonPhrase();
			
			HttpEntity entity = httpResponse.getEntity();
			
			if(entity != null) {
				InputStream instream = entity.getContent();
				response = convertStreamToString(instream);
				
				instream.close();
			}
			
		} catch (ClientProtocolException ex) {
			client.getConnectionManager().shutdown();
			Log.e("ERROR", "Protocol Error: " + ex.toString()); 
		} catch (IOException ex) {
			client.getConnectionManager().shutdown();
			Log.e("ERROR", "IO Error: " + ex.toString()); 
		}
	}
	
	private String convertStreamToString(InputStream is) {		
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		
		String line = null;
		try {
			while((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
		} catch (IOException ex) {
			Log.e("ERROR", "IO Error: " + ex.toString()); 
		}
		
		return sb.toString();
	}
}
